package org.wmq.travelagency02.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.wmq.travelagency02.mapper.TravellerMapper;
import org.wmq.travelagency02.model.Entity.ChatUser;
import org.wmq.travelagency02.model.Entity.TourGroupTraveller;
import org.wmq.travelagency02.model.Entity.Traveller;
import org.wmq.travelagency02.service.ChatUserService;
import org.wmq.travelagency02.service.SignUpService;
import org.wmq.travelagency02.service.TourGroupTravellerService;
import org.wmq.travelagency02.service.TravellerService;

@Service
@RequiredArgsConstructor
public class TravellerServiceImpl extends ServiceImpl<TravellerMapper, Traveller> implements TravellerService {
    @Autowired
    private TravellerMapper travellerMapper;
    @Autowired
    private TourGroupTravellerService tourGroupTravellerService;
    @Autowired
    private SignUpService signUpService;
    @Autowired
    private ChatUserService chatUserService;

    @Override
    public Traveller getById(Long id) {
        LambdaQueryWrapper<Traveller> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Traveller::getId, id).select(
                Traveller::getName, Traveller::getAge, Traveller::getIsAdmin,
                Traveller::getGender, Traveller::getPhone);
        Traveller result = travellerMapper.selectOne(queryWrapper);
        if (result == null) {
            return null;
        }
        result.setId(id);
        return result;
    }

    @Override
    public boolean removeById(Long id) {
        try {
            this.tourGroupTravellerService.lambdaUpdate()
                    .eq(TourGroupTraveller::getTravellerId, id)
                    .remove();
        } catch (Exception e) {
            throw new RuntimeException("删除游客时发生异常，删除旅游团中对应游客的信息失败");
        }
        try {
            this.signUpService.removeByTravellerId(id);
        } catch (Exception e) {
            throw new RuntimeException("删除游客时发生异常，删除报名表中对应游客信息失败");
        }
        return super.removeById(id);
    }

    @Override
    public boolean addChatUserId(String chatUserId, Long id) {
        Traveller traveller = new Traveller();
        traveller.setId(id);
        traveller.setChatUserId(chatUserId);
        return this.updateById(traveller);
    }

    @Override
    public ChatUser getChatUser(Long id) {
        Traveller traveller = this.lambdaQuery().eq(Traveller::getId, id)
                .select(Traveller::getChatUserId).one();
        if (traveller == null) {
            return null;
        }
        if (traveller.getChatUserId() == null) {
            return null;
        }
        return this.chatUserService.getById(traveller.getChatUserId());
    }
}
